package cn.vivi.mapper;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.vivi.domain.Product;
import cn.vivi.domain.vo.QueryData;
import cn.vivi.util.JDBCUtils;

public class ProductMapper {

	private QueryRunner runner = JDBCUtils.getQueryRunner();

	public List<Product> findAll() throws SQLException {
		String sql = "select * from product";
		return runner.query(sql, new BeanListHandler<Product>(Product.class));
	}

	public boolean insert(Product product) throws SQLException {
		String sql = "insert into product values(null, ?, ?, ?, ?, ?)";
		return runner.update(sql, product.getName(), //
				product.getPrice(), //
				product.getDescription(), //
				product.getClassesId(), //
				product.getPicture()) > 0;
	}

	public boolean delete(String id) throws SQLException {
		String sql = "delete from product where id = ?";
		return runner.update(sql, id) > 0;
	}

	public boolean update(Product product) throws SQLException {
		String sql = "update product set name = ?, price = ?, description = ?, classes_id = ?, picture = ? where id = ?";
		return runner.update(sql, product.getName(), //
				product.getPrice(), //
				product.getDescription(), //
				product.getClassesId(), //
				product.getPicture(), //
				product.getId()) > 0;
	}

	public int count(String id) throws SQLException {
		String sql = "select count(*) from product where classes_id = ?";
		return runner.query(sql, new ScalarHandler<Long>(), id).intValue();
	}

	public List<Product> findByClassesId(String id) throws SQLException {
		String sql = "select * from product where classes_id = ?";
		return runner.query(sql, new BeanListHandler<Product>(Product.class), id);
	}

	public List<Product> findByPrice(QueryData data) throws SQLException {
		String sql = "select * from product where price BETWEEN ? AND ?";
		return runner.query(sql, new BeanListHandler<Product>(Product.class), //
				data.getMinPrice(), data.getMaxPrice());
	}

}
